package controllers;

import javax.servlet.http.HttpServletRequest;

import models.desease.Disease;
import models.game.Game;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import dao.UserDAO;

@Controller
public class GameStatusController {

	//ottifcu
	@RequestMapping("/CheckGameStatus")
	public synchronized String checkGameStatus(HttpServletRequest request) {
		
		Game game = (Game) request.getSession().getAttribute("game");
		
		checkForEradicatedDiseases(game);
		game.setGameIsWon(checkIfGameIsWon(game));
		game.setGameIsLost(checkIfGameIsLost(game, request));
		
		return "redirect:/RedirectPlayers";
	}
	
	private void checkForEradicatedDiseases(Game game) {
		for (Disease disease : game.getDiseases().values()) {
			if (disease.getIsCured() == true) {
				if (disease.getInfectionsLeft() == Disease.getNumberOfInfections()) {
					disease.setEradicated(true);
				}
			}
		}
	}
	
	private boolean checkIfGameIsWon(Game game) {
		for (Disease disease : game.getDiseases().values()) {
			if(disease.getIsCured() == false) {
				return false;
			}
		}
		return true;
	}
	
	private boolean checkIfGameIsLost(Game game, HttpServletRequest request) {
		
		for (Disease disease : game.getDiseases().values()) {
			if(disease.getInfectionsLeft() == 0) {
				game.setLoosingReason("The " + disease.getName() + " disease has spread too much!");
				return true;
			}
		}
		if (game.getPlayerDeck().getDeck().size() < 2) {
			game.setLoosingReason("Your team ran out of time! There are no more player cards left in the deck!");
			return true;
		}
		if (game.getOutbreaks() > 8) {
			game.setLoosingReason("A worldwide panic occurred! The diseases have caused too many outbreaks!");
			return true;
		}
		return false;
	}
	
}
